using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.Rendering.Universal;


public class LightControl : MonoBehaviour
{

    private bool _startLight;
    public float lightTime = 2;
    private float _lightTime;
    
    private float startRotation;
    public float targetRotation;
    public float duration;

    private bool isRotation;
    private bool run;
    public LightSwitch lightSwitch;
    private Light2D _light => GetComponent<Light2D>();

    private PlayerController player => GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerController>();

    private void Start()
    {
        _lightTime = lightTime;
        startRotation = transform.rotation.z;
    }

    private void Update()
    {
        if (_startLight && !run)
        {
            _lightTime -= Time.deltaTime;
        }

        if (_light.enabled)
        {
            if (_startLight && _lightTime < 0)
            {
                Debug.Log("player death");
            }
            
            if (!isRotation && !_startLight)
            {
                StartCoroutine(StartRotation());
            }
        }
        
    }

    private void OnTriggerStay2D(Collider2D other)
    {
        if (other.CompareTag("Player") && !player.isLightHide)
        {
            _startLight = true;
            run = false;
        }
    }

    private void OnTriggerExit2D(Collider2D other)
    {
        if (other.CompareTag("Player"))
        {
            run = true;
            _lightTime = lightTime;
        }
    }

    private IEnumerator StartRotation()
    {
        isRotation = true;

        Quaternion start = Quaternion.Euler(0, 0, startRotation);
        Quaternion target = Quaternion.Euler(0, 0, targetRotation);
        
        float elapsedTime = 0;

        while (elapsedTime < duration)
        {
            if (_startLight)
            {
                yield return new WaitUntil(() => run);
                yield return new WaitForSeconds(lightTime);
                _startLight = false;
            }

            float t = elapsedTime / duration;
            transform.rotation = Quaternion.Slerp(start, target, t);
            
            elapsedTime += Time.deltaTime;
            yield return null;
        }

        (startRotation, targetRotation) = (targetRotation, startRotation);

        isRotation = false;
    }
    
}
